<?php

class FormElement_Password extends FormElement
{

  public $hashFunction = 'md5';

  public function render(IDictionary $row, $action)
  {
    $title = ($action == Form::ACTION_EDIT) ? 'Change Password' : 'Password';

    switch ($action) {
      case Form::ACTION_EDIT :
      case Form::ACTION_CREATE :
        $view = $this->getView($action);

        $view->set('title', $title);

        return $view->render();

        break;
    }

    return null;
  }

  public function setDataFromPost($row, $post, $action)
  {
    $a = $this->hash($post->get($this->getName() . '_password_a'));
    $b = $this->hash($post->get($this->getName() . '_password_b'));

    $empty = $this->hash('');

    if ($action == Form::ACTION_EDIT) {
      if ($a != $b) {
        throw new ValidationException('Passwords do not match');
      }
      elseif ($a != $empty) {
        $this->setValue($row, $a);
      }
    }
    elseif ($action == Form::ACTION_CREATE) {
      if ($a != $b) {
        throw new ValidationException('Passwords do not match');
      }
      elseif ($a == $empty || $b == $empty) {
        throw new ValidationException('Inform your password');
      }
    }
  }

  protected function hash($s)
  {
    if ($this->hashFunction) {
      return call_user_func($this->hashFunction, $s);
    }

    return $s;
  }

}

?>